<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/30
 * Time: 18:26
 */

namespace app\console\model;
use app\BaseModel;
use app\model\PackageRecords;
use think\facade\Request;
use think\facade\Cache;
use think\facade\Hook;
use think\facade\Db;
class Config extends BaseModel
{
    /*
    * 配置项更新数据
    */
    public static function renew()
    {
        $data = Request::param();


        //if (empty($data)) {

        $name = get_uniqid();
        $url = time();
        $image = [];

        if (!empty($_FILES)) {
            foreach ($_FILES as $k => $v) {

                if ($v['error'] == 0) {
                    $fileName = $_SERVER['DOCUMENT_ROOT'] . '/config/' . $k . '.jpg';
                    move_uploaded_file($v['tmp_name'], $fileName);
                    $url = Request::domain() . '/config/' . $k . '.jpg?rand=' . mt_rand(1, 100);
                    Cache::set($k, $url);
                    $image[$k] = $url;

                }


            }
        }


//        uploadOne('config5');
//        uploadOne('config6');
        if(!empty($data)){
            foreach ($data as $key => $value) {

                if ($key != 'web_is_clear') {
                    self::where(['varname' => $key])->update(['varvalue' => $value]);
                } else {
                    if ($value == 'Y') {
                        Db::execute("truncate table tp_package_records");
                    }
                }

            }
            $data['logo'] = Request::domain() . '/config/logo.jpg?rand=' . date('md');
            Cache::set('logo',$data['logo']);
            $data['logo2'] = Request::domain() . '/config/logo2.jpg?rand=' . date('md');
            Cache::set('logo2',$data['logo2']);
            file_put_contents(root_path().'/config/web_config.php','<?php return '.var_export($data,true).';');
        }


            //Cache::rm('web');
        return true;
    }

    public static function updateConfigOne($name){

        $controller = Request::controller(true);
        $file = request()->file($name);
        halt($file);
        if (!empty($file)) {
            // 移动到框架应用根目录/uploads/ 目录下
            $info = $file->move('./uploads/'. $controller,$name);
            if($info){
                Cache::set($name,'/uploads/config/'.$info->getSaveName().'?='.mt_rand());
            }
            //dump($info);
        }
    }


    /*
     * 添加新变量
     */
    public static function newVariable()
    {
        $data = Request::instance()->param();

        // 验证器
        //$validate = validate('Config');
//        if (!$validate->check($data)) {
//
//            fail($validate->getError());
//
//        }

        $data['varname'] = 'web_' . $data['varname'];
        $data['create_time'] = date('Y-m-d H:i:s', time());

        $status = (new Config())->save($data);

        if (!empty($status)) {
            //Cache::rm('web');
            return true;
        }
        return false;

    }
}